package org.senseframework.support.open.api.controller.encrypt;

import org.senseframework.support.core.utils.DateUtils;
import org.senseframework.support.core.utils.DigestUtils;
import org.senseframework.support.core.utils.JSONUtils;

import java.util.Date;

/**
 * Author lanjian
 * Email  jianlan@iflytek.com
 */
public class ExchangeTokenImpl implements ExchangeToken {
    private static final String chartset = "utf-8";
    private static final String aesPwd = "Q*rNd@%zwa1Oo4u0";

    /**
     * 暂时先用日期时间实现,后续改造发号器
     * @return
     */
    private String dynamicPwd() {
        String date = DateUtils.dateToString(new Date(), "yyyyMMdd");
        //每1天换一次密码
//        date = date.substring(0,date.length()-1);
        String pwd = DigestUtils.md5(aesPwd + date);
        pwd = pwd.substring(0, 16);
        return pwd;
    }

    @Override
    public String generate(String pwd, String key, int expireSeconds) {
        try {
            ExchangeKey exchangeKey = new ExchangeKey(pwd, key, DateUtils.nowDateTime(), expireSeconds);
            String json = JSONUtils.toJSONString(exchangeKey);
            byte[] _content = SecurityHelper.encryptAES(dynamicPwd(), json.getBytes(chartset));
            return DigestUtils.encodeBase64(_content);
        } catch (Exception ex) {
            throw new EncryptException("generate", ex);
        }
    }

    @Override
    public ExchangeKey from(String token) {
        try {
            byte[] content = token.getBytes(chartset);
            byte[] content_ = SecurityHelper.decryptAES(dynamicPwd(), DigestUtils.decodeBase64(content));
            return JSONUtils.parseObject(new String(content_, chartset), ExchangeKey.class);
        } catch (Exception ex) {
            throw new EncryptException("from", ex);
        }
    }

    public static void main(String[] a) {
        ExchangeTokenImpl exchangeToken = new ExchangeTokenImpl();
        String aaa = exchangeToken.generate("pass", "key", 3600);
        System.out.println(aaa);
        ExchangeKey exchangeKey = exchangeToken.from(aaa);
        exchangeKey.validate();
        System.out.println(exchangeKey);
//        String date = DateUtils.dateToString(new Date(), "yyyyMMddHHmm");
//        date = date.substring(0, date.length() - 1);
//        System.out.println(date);
    }
}
